package com.ktwlrj.logmanage.util;

import com.ktwlrj.logmanage.entity.LogEntity;
import com.ktwlrj.logmanage.service.LogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 日志定时任务
 *
 * @author zhouxuanhong
 * @date 2019-04-19 14:24
 * @since JDK1.8
 */
@Component
@Slf4j
public class LogTimer {
    private final LogService service;

    @Autowired
    public LogTimer(LogService service) {
        this.service = service;
    }

    /**
     * 日志存储类 每5分钟执行一次
     *
     * @author zhouxuanhong
     * @date 2019-04-19 14:27
     */
    @Scheduled(cron = "0 0/5 * * * ?")
    public void saveLog() {
        int size = LogQueue.size();
        if (size > 0) {
            List<LogEntity> list = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                list.add(LogQueue.poll());
            }
            service.insertLogs(list);
        }
    }
}
